package engine.systems.collision.collectable
{
	import ash.core.Engine;
	import ash.core.NodeList;
	import ash.core.System;
	
	import engine.classes.enumerations.SystemPriority;
	import engine.utils.EntityUtils;
	
	public class CollectableSystem extends System
	{
		private var collectables:NodeList;
		private var collectors:NodeList;
		
		public function CollectableSystem()
		{
			this.priority = SystemPriority.COLLISION;
		}
		
		override public function update(time:Number):void
		{
			for(var collector:CollectorNode = this.collectors.head; collector; collector = collector.next)
			{
				if(EntityUtils.sleeping(collector.entity)) continue;
				
				for(var collectable:CollectableNode = this.collectables.head; collectable; collectable = collectable.next)
				{
					if(EntityUtils.sleeping(collectable.entity)) continue;
					
					if(collector.render.display.hitTestObject(collectable.render.display))
					{
						collector.collector.collectables.push(collectable.entity.name);
						collector.collector.collected.dispatch(collector.entity, collectable.entity);
						
						if(collectable.collectable.remove)
						{
							this.group.removeEntity(collectable.entity);
						}
					}
				}
			}
		}
		
		override public function addToEngine(systemManager:Engine):void
		{
			this.collectables 	= systemManager.getNodeList(CollectableNode);
			this.collectors 	= systemManager.getNodeList(CollectorNode);
		}
		
		override public function removeFromEngine(systemManager:Engine):void
		{
			systemManager.releaseNodeList(CollectableNode);
			systemManager.releaseNodeList(CollectorNode);
			
			this.collectables 	= null;
			this.collectors 	= null;
		}
	}
}